import path from 'path'
import fs from 'fs'
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import Components from 'unplugin-vue-components/vite'
import AutoImport from 'unplugin-auto-import/vite'
import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers'
import dayjs from 'dayjs'

const viewsList = fs.readdirSync('./src/views')
// import { visualizer } from 'rollup-plugin-visualizer'
const env = loadEnv('', process.cwd())
const time = dayjs().format('YYYY-MM-DD_HH-mm-ss')
export default defineConfig({
  plugins: [
    vue(),
    // visualizer({ open: true }),
    AutoImport({
      imports: ['vue', 'vue-router', 'pinia'],
      eslintrc: {
        // 项目中使用了 eslint，那么虽然可以正常使用 API 了，但是 eslint 还是会报没有引入的报错。下面的配置可以处理这种情况
        enabled: true // 会在根目录下自动生成 .eslintrc-auto-import.json 文件
      },
      dirs: ['./src/utils', './src/hooks']
    }),
    //自动引入组件
    Components({
      dts: false,
      resolvers: [
        AntDesignVueResolver({
          importStyle: false
        })
      ]
    })
  ],
  //别名
  resolve: {
    extensions: ['.js', '.jsx', '.json', '.vue'],
    alias: {
      '@': path.resolve(__dirname, 'src')
    }
  },
  //构建
  build: {
    commonjsOptions: { transformMixedEsModules: true },
    cssCodeSplit: false,
    sourcemap: false,
    rollupOptions: {
      output: {
        manualChunks(id) {
          for (let i = 0; i < viewsList.length; i++) {
            if (id.includes(`/src/views/${viewsList[i]}`)) {
              return viewsList[i]
            }
          }
          if (id.includes('ant-design-vue')) {
            return 'ant-design-vue'
          } else if (id.includes('zrender')) {
            return 'zrender'
          } else if (id.includes('node_modules/')) {
            return 'vendor'
          } else if (id.includes('/src/components')) {
            return 'components'
          } else if (id.includes('/src/utils')) {
            return 'utils'
          }
        },
        chunkFileNames: 'js/[name]-[hash].js', // 引入文件名的名称
        entryFileNames: () => {
          return `js/[name]-${time}.js`
        }, // 包的入口文件名称
        assetFileNames: '[ext]/[name]-[hash].[ext]' // 资源文件像 字体，图片等
      }
    }
  },
  //服务器
  server: {
    host: '0.0.0.0',
    port: 8100,
    proxy: {
      '/api/v1/ufs': {
        target: 'http://10.11.10.205:7300',
        changeOrigin: true
      },
      '/api/v1/OPTOMETY': {
        target: 'http://10.11.10.201:7229',
        rewrite: (path) => path.replace(/^\/api\/v1/, '/api'),
        changeOrigin: true
      },
      '/api/v1/emr': {
        target: 'http://10.11.10.217:7600',
        changeOrigin: true
      },
      '/api/v1/iframe': {
        target: 'http://imc.fudan-soft.net:8006',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api\/v1\/iframe/, '')
      },
      '/api/v1': {
        target: env.VITE_PROXY || 'http://10.11.10.205:7100',
        changeOrigin: true
      }
    }
  }
})
